<template>
  <div class="nickname-layout">
    <van-nav-bar title="修改昵称" left-arrow @click-left="$router.go(-1)"/>
    <div class="nickname">
      <van-field v-model="nickname" label="昵称：" placeholder="请输入用户名" class="input"/>
      <van-button type="warning" block class="updateBtn" @click="changeNickName" :loading="loading">确认修改
      </van-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "ChangeNickname",

  data() {
    return {
      nickname: "",
      loading: false,
    }
  },

  mounted() {
    let height = document.documentElement.clientHeight || document.body.clientHeight;
    let htmlDom = document.getElementsByClassName("nickname-layout")[0];
    htmlDom.style.height = height + "px";
  },

  methods: {
    //修改昵称
    async changeNickName() {
      this.loading = true;
      if (this.nickname === "") {
        this.$toast("请输入要修改的用户昵称");
        this.loading = false;
        return ;
      }

      //修改信息
      let updateResult = await this.$axios.post(this.$api.updateNickname, {
        userId: this.$store.getters.user.userId,
        nickName: this.nickname
      });
      if (updateResult.status === 200 && updateResult.data.code === 200) {
        this.$toast("修改成功");
        //重新获取用户信息设置相关用户信息
        let getUserInfo = await this.$axios.get(this.$api.current);
        if (getUserInfo.status === 200) {
          //先删除Vuex中的数据
          this.$store.dispatch("clearCurrentState");
          // 再重新赋值
          this.$store.dispatch("setUser", getUserInfo.data);
        }
        setTimeout(() => {
          this.loading = false;
          this.$router.push("/safe");
        }, 500);
      }
    }
  }
}
</script>

<style scoped lang="less">
.nickname-layout {
  background-color: #fafafa;

  .van-nav-bar {
    background-color: #fafafa;
  }

  .nickname {
    margin: 10px 0px;
    padding: 0px 5px;

    .input {
      border-radius: 7px;
    }

    .updateBtn {
      width: 96%;
      border-radius: 10px;
      margin: 0 auto;
      margin-top: 1.25rem;
    }

    .van-field__label {
      width: 3.2rem;
    }
  }
}
</style>